#include "graph-node.h"
#include "model-helper.h"
#include "section-descendant-view.h"
#include "section-descendant-model.h"
#include "section-info.h"

SectionDescendantView::SectionDescendantView(QWidget *parent) :
    QListView(parent), m_model(new SectionDescendantModel(this))
{
    setModel(m_model);
    setSelectionMode(QAbstractItemView::SingleSelection);
    connect (selectionModel(), &QItemSelectionModel::selectionChanged, this, &SectionDescendantView::selectionChanged);
}

const GraphNode<SectionInfo> *SectionDescendantView::selectedSectionNode() const
{
    if (!selectionModel()->hasSelection())
        return 0;
    if (!ModelHelper::isOnlyOneRowSelected(this))
        return 0;
    return m_model->sectionNode()->childNodes().at(selectionModel()->selectedRows().at(0).row());
}

GraphNode<SectionInfo> *SectionDescendantView::selectedSectionNode()
{
    if (!selectionModel()->hasSelection())
        return 0;
    if (!ModelHelper::isOnlyOneRowSelected(this))
        return 0;
    return m_model->sectionNode()->childNodes().at(selectionModel()->selectedRows().at(0).row());
}

void SectionDescendantView::setSectionNode(GraphNode<SectionInfo> *sectionNode)
{
    m_model->setSectionNode(sectionNode->parentNode());
    m_originalSectionNode = sectionNode;
}

void SectionDescendantView::initialize()
{
    m_model->initialize();

    QList<GraphNode<SectionInfo>*> descendants = m_model->sectionNode()->childNodes();
    int i = 0;
    for (; i < descendants.size(); i++)
    {
        if (descendants.at(i) == m_originalSectionNode)
            break;
    }
    selectionModel()->select(selectionModel()->model()->index(i, 0), QItemSelectionModel::Select);
    setCurrentIndex(model()->index(i, 0));
}

void SectionDescendantView::selectionChanged()
{
    emit sectionChosen(m_model->sectionNode()->childNodes().at(selectionModel()->selectedRows().at(0).row()));
}
